<?php
class logger{
	/**
	 * 数据库句柄
	 */
	protected $_db = null;
	/**
	 * 系统日志的数据表
	 */
	protected $_table = null;
	/**
	 * 日志信息
	 * @var Array
	 */
	protected $_data = array();
	
	function __construct($db = null,$table = 'logs') {
		if($db !== null){
			$this->_db = $db;
		}else{
			global $cbdb;
			$this->_db = $cbdb;
		}
		$this->_table = $table;
		register_shutdown_function(array(&$this, "__destruct"));
	}
	
	/**
	 * 记录日志 到缓存
	 * @param unknown_type $content
	 * @param unknown_type $type
	 * @param unknown_type $username
	 */
	function log($content,$type = 'system',$username = ''){
		if($username == ''){
			if(isset($GLOBALS['user'])&&is_object($GLOBALS['user'])){
				$username = $GLOBALS['user']->username;
			}
		}
		$this->_data[]=array('logtype'=>$type,
							 'logcontent'=>$content,
							 'username'=>$username,
							 'ip'=>IP_ADDRESS,
							 'logtime'=>TIME_STAMP
						);
	}
	
	/**
	 * 清空日志缓存
	 */
	function clear(){
		$this->_data = array();
	}
	
	/**
	 * 删除超过指定天数的日志记录
	 */
	function delete ($day = 30){
		$time = TIME_STAMP - $day*60*60*24;
		return $this->_db->query("DELETE FROM `{#cbdbPrefix}$this->_table` WHERE logtime<$time");
		
	}
	
	/**
	 * 写入数据库
	 */
	function write(){
		foreach ($this->_data as $log){
			$this->_db->insert('{#cbdbPrefix}'.$this->_table,$log);
		}
	}
	
	/**
	 * 对象注消时执行
	 */
	function __destruct(){
		if(!empty($this->_data)){
			$this->write();
			$this->_data = array();
		}
	}
}